from fastapi import FastAPI
from fastapi.responses import Response
from fastapi import HTTPException
from fastapi.templating import Jinja2Templates

from . import plugin
from . import login
from . import session_save
from . import ws_connect
from .userobj import User


def main(app: FastAPI, templates: Jinja2Templates):  # 桌面
    HOME_TEMPLATE = templates.TemplateResponse(
        "home.html", {"request": {}})  # 预渲染模板
    JS_TEMPLATE = Response(
        content=plugin.addition_js_lst, media_type="application/javascript")
    CSS_TEMPLATE = Response(
        content=plugin.addition_css_lst, media_type="text/css")

    # 注册 websocket
    ws_connect.main(app, templates)

    # 绑定主页
    @app.get("/")
    @login.check_cookie
    async def root():
        return HOME_TEMPLATE

    # 图标api
    @app.get("/api/home/icon")
    @login.check_cookie
    async def get_icons(user: User):
        icons_list = [
            {
                "name": v[0],
                "image": "/api/home/icon/"+k+"/icon.png",
                "id":  k
            } for k, v in plugin.icons_access.items() if (await user.get_permission("//plugin/"+k) > 0)
        ]
        icons_list.sort(key=lambda v: v["id"])
        return ({
            "icons": icons_list
        })

    # 图标api-图片
    @app.get("/api/home/icon/{icon_id}/icon.png")
    @login.check_cookie
    async def get_image(icon_id):
        icon_obj = plugin.icons_access.get(icon_id, None)
        if icon_obj is None:
            return HTTPException(status_code=404, detail="Not Found")
        return Response(icon_obj[1], media_type="image/png")

    # 注入js api
    @app.get("/api/home/.js")
    @login.check_cookie
    async def get_js():
        return JS_TEMPLATE

    # 注入css api
    @app.get("/api/home/.css")
    @login.check_cookie
    async def get_css():
        return CSS_TEMPLATE

    # 获取iframe内容
    @app.get("/api/plugin/{plugid}/iframe/{pluginurl}")
    @login.check_cookie
    async def load_plugin(plugid: str, pluginurl: str):
        plug_obj = plugin.template_access.get(plugid, {}).get(pluginurl, {})
        if plug_obj is None:
            return HTTPException(status_code=404, detail="Not Found")
        return plug_obj

    session_save.load_session(app)  # 还原会话


if __name__ == "__main__":
    print("This program cannot be run as a script. Please run the main.py file instead.")
